import { queryParamArea } from '@/services/file';
import { Select } from 'antd';
import React, { useEffect, useState } from 'react';

const { Option } = Select;

export interface ItemPoprs {
  key?: string;
  value?: string;
}

interface AddressSelectPorps {
  value?: ItemPoprs;
  onChange?: () => void;
  width?: number;
  size?: any;
  disabled?: boolean;
}

type AddressType = {
  province?: any[] | number;
  city?: any[] | number;
  area?: any[] | number;
};

const AddressSelect: React.FC<AddressSelectPorps> = props => {
  const { value, width = 120, size = 'default', disabled } = props;
  const [address, setAddress] = useState<AddressType>({
    province: [],
    city: [],
    area: [],
  });
  const [addressValue, setAddressValue] = useState<AddressType>({
    province: undefined,
    city: undefined,
    area: undefined,
  });
  const [arrItem, setArrItem] = useState<ItemPoprs[]>([]);

  /**
   * 初始化加载省数据
   */
  useEffect(() => {
    // 默认加载省级数据
    queryParamArea({}).then(res => {
      if (res.responseCode == 200) {
        address.province = res.data;
        setAddress(() => {
          return {
            ...address,
          };
        });
      }
    });
  }, []);

  /**
   * 当props.value发生改变时设置所属回显值
   */
  useEffect(() => {
    if (value && Array.isArray(value) && value?.length) {
      let arrValue: any[] = value;
      let attr: any = [];
      //使用promise 实现获取市或区
      arrValue.forEach((el: string, index: number) => {
        attr.push(
          new Promise((resolve, reject) => {
            queryParamArea({ parentId: value?.[index]?.value, level: index + 2 }).then(res => {
              if (res?.responseCode == 200) {
                resolve(res?.data);
              } else {
                reject([]);
              }
            });
          }),
        );
      });

      Promise.all(attr).then(res => {
        //设置市区的展示数据
        setAddress(() => {
          return {
            ...address,
            city: res?.[0] ?? [],
            area: res?.[1] ?? [],
          };
        });
        // 设置省市区的展示文字
        setAddressValue(() => {
          return {
            province: value?.[0]?.value,
            city: value?.[1]?.value,
            area: value?.[2]?.value,
          };
        });
      });
    }

    return () => {
      //设置市区的展示数据
      setAddress(() => {
        return {
          ...address,
          city: [],
          area: [],
        };
      });
      // 设置省市区的展示文字
      setAddressValue(() => {
        return {
          province: undefined,
          city: undefined,
          area: undefined,
        };
      });
    };
  }, [value]);

  /**
   * 当选择省市区做的操作
   * @param item
   * @param key
   * @param arr
   * @param index
   */
  const onChange = (item: any, key: string, arr: any[], index: number) => {
    setAddressValue(() => {
      return {
        ...addressValue,
        [key]: item,
      };
    });

    //设置返回值
    arrItem[index] = {
      key: undefined,
      value: undefined,
    };
    // 设置state
    setArrItem(() => {
      return arrItem;
    });

    if (item) {
      // 获取当前与value相等的对象
      let obj = address[key].find((el: any) => el.areaId == item);
      //设置返回值
      arrItem[index] = {
        key: obj.areaName,
        value: obj.areaId,
      };
      // 设置state
      setArrItem(() => {
        return arrItem;
      });
      // 判断如果第大于第三级 就不再请求
      if (obj?.level <= 2) {
        queryParamArea({ parentId: obj?.areaId, level: obj?.level * 1 + 1 }).then(res => {
          if (res.responseCode == 200) {
            // 因为省的数据已经存在所以去除第一个
            if (index <= 1) {
              address[arr[index + 1]] = res.data;
              setAddress(() => {
                return {
                  ...address,
                };
              });
            }
          }
        });
      }
    } else {
      // 当点击市的清空按钮时清空区的所有数据
      if (index == 1) {
        setAddress(() => {
          return {
            ...address,
            area: [],
          };
        });
        setAddressValue(() => {
          return {
            province: addressValue.province,
            city: undefined,
            area: undefined,
          };
        });
      }
    }
    // 如果点击省的清空按钮则清空所有数据
    if (index == 0) {
      setAddress(() => {
        return {
          ...address,
          city: [],
          area: [],
        };
      });
      setAddressValue(() => {
        return {
          province: item,
          city: undefined,
          area: undefined,
        };
      });
    }
    props?.onChange?.(arrItem);
  };
  return (
    <>
      {Object.keys(address).map((el, index) => (
        <Select
          placeholder="未选择"
          onChange={e => {
            onChange(e, el, Object.keys(address), index);
          }}
          allowClear
          style={{ width, marginRight: 15 }}
          size={size}
          value={addressValue[el]}
          key={el + '_id*8090041'}
          disabled={disabled}>
          {address?.[el]?.map((els: any) => (
            <Option key={els.areaId + '_id*8090041'} value={els.areaId}>
              {els.areaName}
            </Option>
          ))}
        </Select>
      ))}
    </>
  );
};

export default AddressSelect;
